/*
 * Copyright (C) 2019-2020 Alibaba Group Holding Limited
 */
#include <aos/aos.h>
#include <aos/kv.h>
#include <uservice/eventid.h>
#include <uservice/uservice.h>
#include "aos/kernel.h"
#include "app_main.h"
#include "http.h"
#include "network.h"
#include <aos/debug.h>
#include "cJSON.h"


#define CONFIG_WEATHER_TASK_STACK_SIZE  2*1024
#define WEATHER_ASYNC_BUF_SIZE          512
#define WEATHER_SIZE                    256

#define TAG "APP_WEATHER"

#define STATUS "status"
#define LIVES  "lives"
#define WEATHER "weather"
#define TEMP "temperature"
#define TIME "reporttime"

#define WEATHER_URL    "http://restapi.amap.com/v3/weather/weatherInfo?city=210600&key=7132ca975bd42cfec18917f2adf43acd" 

  //"https://api.seniverse.com/v3/weather/now.json?key=STvZSMKt7CxPsJA-A&location=dandong&language=zh-Hans&unit=c"


 //"http://restapi.amap.com/v3/weather/weatherInfo?city=440306&key=624d77fce9f6a6b4ca01158b382a443b"  f37ca171a7f7770fde1f30bb3e86fe0b


uint8_t*  weather_buffer;
aos_sem_t weather_sem;
aos_queue_t weather_queue;



// sunny晴
// cloudy多云 
// overcast阴天 
// light rain 小雨 
// moderate rain 中雨 
// heavy rain 大雨 
// moderate snow中雪 
// heavy snow 大雪 
// light snow小雪 
// rainstorm暴雨 
// thunderstorm雷雨 
// fog雾

static char *translate_weather_type_in_ascii(const char *weather_type)
{
    char *weather_info;
    weather_info = malloc(64);
    if(!strcmp("多云",weather_type))
    {
        strcpy(weather_info, "Cloudy");
         
    }else if(!strcmp("晴",weather_type))
    {
        strcpy(weather_info, "Sunny");
    }else if(!strcmp("小雨",weather_type))
    {
        strcpy(weather_info, "Light Rain");
    }else if(!strcmp("雾",weather_type))
    {
        strcpy(weather_info, "Fog");
    }else if(!strcmp("阴",weather_type))
    {
        strcpy(weather_info, "Overcast");
    }else{
        strcpy(weather_info, "Nothings is Found!");
        LOG("weather_type:\n%s\n", weather_type);
    }

    return weather_info;
}


static void parse_http_data(char *http_data)
{
    app_weather_t app_weather_data;

    cJSON *root;
    cJSON *status;
    cJSON *lives;
    cJSON *tmp_obj; 
    cJSON *live_obj;
    char *str_tmp;
    int size;


    root = cJSON_Parse(http_data);
    if(root)
    {
        LOGD(TAG, "JSON_data:\n%s\n", cJSON_Print(root));
        status = cJSON_GetObjectItem(root, STATUS);
        if(status)
        {
            LOGD(TAG, "status:%d,%s\r\n",atoi(status->valuestring), status->valuestring);
            lives = cJSON_GetObjectItem(root, LIVES);
            if(lives)
            { 
                size = cJSON_GetArraySize(lives);
                LOGD(TAG, "!!size:%d\r\n",size);
                for(int i=0;i<size;i++)
                {
                    live_obj = cJSON_GetArrayItem(lives, i);
                    if(live_obj)
                    {
                        tmp_obj = cJSON_GetObjectItem(live_obj, WEATHER);
                        str_tmp = translate_weather_type_in_ascii(tmp_obj->valuestring);
                        sprintf(app_weather_data.info, "WeatherInfo:%s", str_tmp); 
                        free(str_tmp);
                        LOGD(TAG, "%s\r\n",app_weather_data.info);

                        tmp_obj = cJSON_GetObjectItem(live_obj, TIME);
                        sprintf(app_weather_data.time, "Time:%s", tmp_obj->valuestring); 
                        LOGD(TAG, "%s\r\n",app_weather_data.time);
                                                
                        tmp_obj = cJSON_GetObjectItem(live_obj, TEMP);
                        sprintf(app_weather_data.temperature, "Temperature:%s", tmp_obj->valuestring); 
                        LOGD(TAG, "%s\r\n",app_weather_data.temperature);
                    }
                }
            }
        }
    }
    cJSON_Delete(root); 
    aos_queue_send(&weather_queue, &app_weather_data, sizeof(app_weather_t));
}

static int get_weather_url(char *weathe_url, int len)
{
    int ret = -1;

    ret = aos_kv_getstring("weatherurl", weathe_url, len);
    if (ret < 0) {
        strcpy(weathe_url, WEATHER_URL);
    }

    return ret;
}

static int aos_http_get_weather(void) {
	
    LOG("time:\n%s\n", "aos_http_get_weather");
    http_t *http;
    // char *payload;
    char *body;
    int value_len;
    char *cptr;
    char getvalue[64];
    int rc;
    int ret;


    memset(getvalue, 0, sizeof(getvalue));
    get_weather_url(getvalue, sizeof(getvalue));
	LOG("%s %d\n", getvalue, sizeof(getvalue));
    if ((http = http_init(getvalue)) == NULL) {
        LOGD(TAG, "error http init");
        return -1;
    }

    memset(http->buffer, 0, 2048);
    http->buffer_offset = 0;
    http_head_sets(http, "Host", http->host);
    http_head_sets(http, "Connection", "keep-alive");
    http_head_sets(http, "Content-Type", "application/json");
    http_head_sets(http, "Cache-Control", "no-cache");

    http_get(http,10000);

    http_wait_resp(http, &body, 10000);

    LOGD(TAG, "resp body: %200s", body);

    parse_http_data(body);

    http_deinit(http);
    return 0;
}


static int weather_queue_init(void)
{
    int rc = -1;
    if (weather_buffer == NULL) {
        weather_buffer = aos_malloc(WEATHER_ASYNC_BUF_SIZE);
        if (weather_buffer != NULL) {
            rc = aos_queue_new(&weather_queue, weather_buffer, WEATHER_ASYNC_BUF_SIZE, WEATHER_SIZE);
            if (0 != rc) {
                aos_free(weather_buffer);
                weather_buffer = NULL;
            }
        }
    }
    return rc;
}

// extern int flag;

static void get_weather_task(void)
{
    LOGD(TAG, "get_weather_begin..... \r\n ");
	uint8_t dd;
    while(1) 
    {
        LOGD(TAG, "getting..... \r\n ");
		
        //aos_sem_wait(&weather_sem, AOS_WAIT_FOREVER);
        LOGD(TAG, "GET weather_sem \r\n ");
        aos_http_get_weather();
		for(dd=0;dd<120;dd++)
		{
			aos_msleep(1000);
		}
		
		
    }
    LOGD(TAG, "exit get_weather_task !!!\r\n ");
    aos_task_exit(0);
}

static int weather_start(void)
{
    aos_task_t task;
    if (aos_task_new_ext(&task, "get-weather", get_weather_task, NULL, CONFIG_WEATHER_TASK_STACK_SIZE, AOS_DEFAULT_APP_PRI + 5) != 0) {
        return -1;
    }
    LOGD(TAG, "creat task:get-weather successful\r\n ");
    return 0;
}


void app_weather_init(void)
{
	
	//LOGD(TAG, "###############################################");
    if(weather_queue_init() != 0)
    {
        LOGD(TAG, "creat queue:weather_queue failed\r\n ");
    }

    if (aos_sem_new(&weather_sem, 0) != 0)
    {
        LOGD(TAG, "creat sem:weather_sem failed\r\n ");
    }

    if (aos_sem_is_valid(&weather_sem) == 0)
    {
        LOGD(TAG, "aos_sem_is_valid\r\n ");
    }

}

void app_weather_start(void)
{
    weather_start();
}
